package com.dge.app.ui

import android.content.ClipData
import android.content.ClipboardManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import cat.ereza.customactivityoncrash.CustomActivityOnCrash
import cat.ereza.customactivityoncrash.config.CaocConfig
import com.dge.app.R
import com.dge.app.databinding.ActivityCrashBinding
import com.dge.common.base.view.BaseActivity
import com.dge.common.common.AppConfig.getVersionCode
import com.dge.common.common.AppConfig.getVersionName
import com.dge.common.common.AppConfig.isPublishRelease
import com.dge.common.extentions.singleClick
import com.dge.common.utils.Utils
import timber.log.Timber
import java.util.Properties

/**
 * 崩溃捕捉界面
 */
class CrashActivity : BaseActivity<ActivityCrashBinding>() {
    private var mConfig: CaocConfig? = null

    /**
     * 使用Properties来保存设备的信息和错误堆栈信息
     */
    private val mDeviceCrashInfo = Properties()
    private var mCrashInfo: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Utils.setImmersiveStatusOrNavBar(this, false, true, true)
        binding.btnCrashLog.singleClick { onClick(it) }
        binding.btnCrashRestart.singleClick { onClick(it) }
        if (isPublishRelease()) {
            binding.btnCrashLog.text = "关闭"
        }
        mConfig = CustomActivityOnCrash.getConfigFromIntent(intent)
        if (mConfig == null) {
            // 这种情况永远不会发生，只要完成该活动就可以避免递归崩溃。
            finish()
        }
        mCrashInfo = CustomActivityOnCrash.getAllErrorDetailsFromIntent(this@CrashActivity, intent)
        val sb = StringBuilder()
        sb.append("Android version：").append(Build.VERSION.RELEASE).append("\n")
        sb.append("Version code：").append(getVersionCode()).append("\n")
        sb.append(mCrashInfo)
        mCrashInfo = sb.toString()
        mDeviceInfo = collectCrashDeviceInfo()
        Timber.v("onCreate 全局异常信息: $mCrashInfo")
        Timber.v("onCreate 设备信息: $mDeviceInfo")
        //        if (BuildConfig.DEBUG) {
//            new Thread(() -> {
//                //保存错误报告文件
//                LogToFile.w("KDMH", mCrashInfo + "\n设备信息：" + mDeviceInfo);
//            }).start();
//        }
//        sendRequestPost(mCrashInfo!!)
    }

    fun onClick(v: View) {
        when (v.id) {
            R.id.btn_crash_restart -> CustomActivityOnCrash.restartApplication(
                this@CrashActivity,
                mConfig!!
            )

            R.id.btn_crash_log -> {
                if (isPublishRelease()) {
                    finish()
                    return
                }
                val dialog = AlertDialog.Builder(this@CrashActivity)
                    .setTitle("错误详情")
                    .setMessage(mCrashInfo)
                    .setPositiveButton("关闭", null)
                    .setNeutralButton("复制日志") { dialog, which -> copyErrorToClipboard() }
                    .show()
                val textView = dialog.findViewById<TextView>(android.R.id.message)
                textView?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
            }

            else -> {
            }
        }
    }

    /**
     * 复制报错信息到剪贴板
     */
    private fun copyErrorToClipboard() {
        ContextCompat.getSystemService(
            this,
            ClipboardManager::class.java
        )!!.setPrimaryClip(ClipData.newPlainText("错误信息", mCrashInfo))
    }

    /**
     * 收集程序崩溃的设备信息
     */
    private fun collectCrashDeviceInfo(): String {
        val sb = StringBuffer()
        mDeviceCrashInfo[VERSION_NAME] = getVersionName()
        mDeviceCrashInfo[VERSION_CODE] = "" + getVersionCode()
        //使用反射来收集设备信息.在Build类中包含各种设备信息
        val fields = Build::class.java.declaredFields
        for (field in fields) {
            try {
                field.isAccessible = true
                mDeviceCrashInfo[field.name] = "" + field[null]
                sb.append(field.name).append("：").append(field[null]).append("\r\n")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return sb.toString()
    }

    private fun setFullScreenWindowLayout(window: Window) {
        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.statusBarColor = Color.TRANSPARENT
        }
        //设置页面全屏显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val lp = window.attributes
            lp.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            //设置页面延伸到刘海区显示
            window.attributes = lp
        }
    }

    companion object {
        private const val VERSION_NAME = "versionName"
        private const val VERSION_CODE = "versionCode"
        private const val STACK_TRACE = "STACK_TRACE"
        var mDeviceInfo: String? = null
//        fun sendRequestPost(msg: String) {
//            //Type 0：PC 1：安卓 2：IOS
//            val submitData = ("LogContent=" + msg + "&Type=1" + "&DevInfo=" + mDeviceInfo
//                    + "&Uid=" + SPUtils.getString(
//                APP.context,
//                Constants.PREF_KEY_USER_ID
//            ) + "&VersionName=" + getVersionName()
//                    + "&SystemVersion=Android" + Build.VERSION.RELEASE)
//            val params = HashMap<String, Any>()
//            params["checkCode"] = NdkMethods.getSecretKey()
//            params["logcontent"] = msg
//            params["logtype"] = 5// 1:android（橙交） 2:im 3:ios 4:pc 5.android(橙交救援)
//            params["nickname"] = UserInfoMgr.nickName
//            params["property"] = mDeviceInfo ?: ""
//            params["userid"] = SPUtils.getString(APP.context, Constants.PREF_KEY_USER_ID)
//            HttpUtils.postWithHeaderToken(URLConstants.uploadLog, null, params, object : Callback {
//                override fun onSuccess(any: Any) {
//                }
//
//                override fun onError(code: Int, msg: String) {
//                }
//
//                override fun onFailure(e: Exception) {
//                }
//            }, BaseBean::class.java)
//        }
    }
}